package com.lcy.codesandbox;

import com.lcy.codesandbox.model.ExecuteCodeRequest;
import com.lcy.codesandbox.model.ExecuteCodeResponse;
import com.lcy.codesandbox.model.JudgeInfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


public class LocalCodeSandbox implements CodeSandBox {

	@Override
	public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) throws IOException {
//		CodeSandBox codeSandbox = CodeManager.getCodeSandbox(executeCodeRequest.getLanguage());
//		return codeSandbox.executeCode(executeCodeRequest);
		// 参数校验
		if (executeCodeRequest == null || executeCodeRequest.getCode() == null || executeCodeRequest.getCode().trim().isEmpty()) {
			return createErrorResponse("代码不能为空");
		}

		try {
			// 1. 安全写入文件
			Path sourcePath = Paths.get("Main.java");
			byte[] codeBytes = executeCodeRequest.getCode().getBytes(StandardCharsets.UTF_8); // 明确指定编码
			Files.write(sourcePath, codeBytes);

			// 2. 编译代码（完整实现）
			Process compileProcess = new ProcessBuilder("javac", "Main.java")
					.redirectErrorStream(true)
					.start();

			String compileOutput = readProcessOutput(compileProcess);
			int compileExitCode = compileProcess.waitFor();

			if (compileExitCode != 0) {
				return createErrorResponse("编译失败: " + compileOutput);
			}

			// 3. 执行代码（完整实现）
			Process runProcess = new ProcessBuilder("java", "Main")
					.redirectErrorStream(true)
					.start();

			if (!runProcess.waitFor(5, TimeUnit.SECONDS)) {
				runProcess.destroy();
				return createErrorResponse("执行超时");
			}

			String output = readProcessOutput(runProcess);
			return createSuccessResponse(output);

		} catch (Exception e) {
			return createErrorResponse("系统错误: " + e.getMessage());
		}
	}

	// 辅助方法：读取进程输出
	private String readProcessOutput(Process process) throws IOException {
		try (BufferedReader reader = new BufferedReader(
				new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
			return reader.lines().collect(Collectors.joining("\n"));
		}
	}

	// 辅助方法：创建成功响应
	private ExecuteCodeResponse createSuccessResponse(String output) {
		ExecuteCodeResponse response = new ExecuteCodeResponse();
		response.setOuputList(List.of(output));

		JudgeInfo judgeInfo = new JudgeInfo();
		judgeInfo.setMessage("执行成功");


		response.setJudgeInfo(judgeInfo);
		return response;
	}

	// 辅助方法：创建错误响应
	private ExecuteCodeResponse createErrorResponse(String errorMessage) {
		ExecuteCodeResponse response = new ExecuteCodeResponse();
		response.setOuputList(List.of());

		JudgeInfo judgeInfo = new JudgeInfo();
		judgeInfo.setMessage(errorMessage);


		response.setJudgeInfo(judgeInfo);
		return response;
	}

}